/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package meg.ejb.impl;

import java.io.Serializable;
import javax.ejb.EJB;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import meg.dto.PlayerException;
import meg.ejb.entity.Player;
import meg.ejb.inter.DigestUtil;
import meg.ejb.inter.PlayerInfo;

/**
 *
 * @author radek
 */
@Stateful
public class PlayerInfoBean implements PlayerInfo, Serializable {

    private static final int PLAYER_UNLOGGED_ID = -1;
    
    @PersistenceContext
    private EntityManager entityManager;

    @EJB
    private DigestUtil digester;

    private int playerId = PLAYER_UNLOGGED_ID;

    @Override
    public void login(String login, String password) throws PlayerException {
        Query q = entityManager.createQuery("SELECT p.id FROM Player p WHERE p.login = ?1 AND p.password = ?2");
        q.setParameter(1, login);
        q.setParameter(2, digester.getPasswordDigest(password));
        try {
            playerId = (Integer)q.getSingleResult();
        } catch (NoResultException e) {
            throw new PlayerException();
        }
    }

    @Remove
    @Override
    public void logout() {
        playerId = PLAYER_UNLOGGED_ID;
    }

    @Override
    public Player getLoggedPlayer() {
        if(playerId == PLAYER_UNLOGGED_ID) {
            throw new IllegalStateException();
        } else {
            return entityManager.find(Player.class, playerId);
        }
    }

    @Override
    public boolean isPlayerLogged() {
        return playerId != PLAYER_UNLOGGED_ID;
    }

}
